/*
 *
 *      Copyright (c) 2018-2025, madp All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: 成都文思海辉金信软件有限公司
 *
 */

package com.pactera.madp.admin.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pactera.madp.admin.api.constant.CrmDictTypeConstants;
import com.pactera.madp.admin.api.dto.SysDictDto;
import com.pactera.madp.admin.api.dto.SysDictItemDto;
import com.pactera.madp.admin.api.entity.SysDict;
import com.pactera.madp.admin.api.entity.SysDictItem;
import com.pactera.madp.admin.service.SysDictItemService;
import com.pactera.madp.admin.service.SysDictService;
import com.pactera.madp.common.core.constant.CacheConstants;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.log.annotation.SysLog;
import com.pactera.madp.common.security.annotation.Inner;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.baomidou.mybatisplus.core.toolkit.Wrappers.query;

/**
 * <p>
 * 字典表 前端控制器
 * </p>
 *
 * @author madp
 * @since 2019-03-19
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/dict")
@Api(value = "dict", tags = "字典管理模块")
public class SysDictController {
	private final SysDictService sysDictService;
	private final SysDictItemService sysDictItemService;


	/**
	 * 查询全部字典
	 * @return
	 */
	@GetMapping("/all")
	@Cacheable(value = CacheConstants.DICT_DETAILS, key = "'SysDict'", unless = "#result == null")
	public R getAllDict(){
		return R.ok(sysDictService.list());
	}


	/**
	 * 通过ID查询字典信息
	 *
	 * @param id ID
	 * @return 字典信息
	 */
	@GetMapping("/{id}")
	public R getById(@PathVariable Integer id) {
		return R.ok(sysDictService.getById(id));
	}


	/**
	 * 分页查询字典信息
	 *
	 * @param page 分页对象
	 * @return 分页对象
	 */
	@GetMapping("/page")
	public R<IPage> getDictPage(Page page, SysDict sysDict) {
		return R.ok(sysDictService.page(page, query(sysDict)));
	}


	/**
	 * 添加字典
	 *
	 * @param sysDict 字典信息
	 * @return success、false
	 */
	@SysLog("添加字典")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys_dict_add')")
	@CacheEvict(value = CacheConstants.DICT_DETAILS, key = "'SysDict'")
	public R save(@Valid @RequestBody SysDict sysDict) {
		return R.ok(sysDictService.save(sysDict));
	}


	/**
	 * 修改字典
	 *
	 * @param sysDictDto 字典信息
	 * @return success/false
	 */
	@PutMapping
	@SysLog("修改字典")
	@PreAuthorize("@pms.hasPermission('sys_dict_edit')")
	@Caching(evict = {
			@CacheEvict(value = CacheConstants.DICT_DETAILS, key = "'SysDictItem:' + #sysDictDto.oldType", condition = "#sysDictDto.type ne #sysDictDto.oldType"),
			@CacheEvict(value = CacheConstants.DICT_DETAILS, key = "'SysDict'")
	})
	public R updateById(@RequestBody SysDictDto sysDictDto) {

		List<SysDictItem> list = null;
		//只有type改变才清空缓存
		if(null != sysDictDto.getType() && !sysDictDto.getType().equals(sysDictDto.getOldType())){
			//查询所有关联type的item
			Map<String,Object> query = new HashMap<>();
			query.put("type", sysDictDto.getOldType());
			list = (List)sysDictItemService.listByMap(query);
		}

		SysDict sysDict = new SysDict();
		BeanUtils.copyProperties(sysDictDto, sysDict);
		boolean flag = sysDictService.updateById(sysDict);

		//删除type关联的item缓存
		if(list != null){
			list.forEach(item -> {
				sysDictItemService.removeCacheByType(item);
			});
		}

		return R.ok(flag);
	}


	/**
	 * 通过type删除字典, 并且清除相关缓存
	 * @param type
	 * @return
	 */
	@SysLog("通过type删除字典")
	@DeleteMapping("/type/{type}")
	@PreAuthorize("@pms.hasPermission('')")
	@Caching(evict = {
			@CacheEvict(value = CacheConstants.DICT_DETAILS, key = "'SysDictItem:' + #type"),
			@CacheEvict(value = CacheConstants.DICT_DETAILS, key = "'SysDict'")
	})
	public R removeByType(@PathVariable String type) {
		//查询所有关联type的item
		Map<String,Object> query = new HashMap<>();
		query.put("type", type);
		List<SysDictItem> list = (List)sysDictItemService.listByMap(query);

		//删除数据库字典项
		sysDictItemService.removeByMap(query);

		//删除数据库字典
		boolean flag = sysDictService.removeByMap(query);

		//删除type关联的item缓存
		if(list != null){
			list.forEach(item -> {
				sysDictItemService.removeCacheByType(item);
			});
		}

		return R.ok(flag);
	}

	//------------------------------------------------------------------------------------------------------------------

	/**
	 * 通过字典类型查找字典
	 *
	 * @param type 类型
	 * @return 同类型字典
	 */
	@GetMapping("/type/{type}")
	@Cacheable(value = CacheConstants.DICT_DETAILS, key = "#type")
	public R getDictByType(@PathVariable String type) {
		return R.ok(sysDictItemService.list(Wrappers
				.<SysDictItem>query().lambda()
				.eq(SysDictItem::getType, type)));
	}

	/**
	 * 通过字典类类型|字典值对象查询字典项
	 * @param type --字典类型关键字
	 * @param value --字典值
	 * @return 对应的字典项对象
	 */
	@GetMapping("/item/value/{type}/{value}")
	@Cacheable(value = CacheConstants.DICT_DETAILS, key = "'SysDictItem:' + #type + ':' + #value", unless = "#result == null")
	public R<SysDictItem> getDictItem(@PathVariable String type, @PathVariable String value){
		SysDictItem sysDictItem = new SysDictItem();
		sysDictItem.setType(type);
		sysDictItem.setValue(value);
		log.info("开始查询字典项:" + type + ":" + value);
		sysDictItem = sysDictItemService.getOne(Wrappers.query(sysDictItem));
		log.info("查询完成:" + JSONObject.toJSONString(sysDictItem));
		return R.ok(sysDictItem);
	}


	/**
	 * 通过字典类型查找字典项
	 *
	 * @param type 类型
	 * @return 同类型字典项
	 */
	@GetMapping("/item/type/{type}")
	@Cacheable(value = CacheConstants.DICT_DETAILS, key = "'SysDictItem:' + #type", unless = "#result == null")
	public R<List<SysDictItem>> getDictByItemType(@PathVariable String type) {
		return R.ok(sysDictItemService.list(Wrappers
				.<SysDictItem>query().lambda()
				.eq(SysDictItem::getType, type)));
	}


	/**
	 * 获取CRM客户数据字典
	 *
	 * @return crm客户数据字典
	 */
	@Inner(value = false)
	@GetMapping("/crm-cust-dict/list")
	public List<SysDictItem> getCrmCustDict () {
		return sysDictItemService.list(Wrappers
				.<SysDictItem>query().lambda()
				.in(SysDictItem::getType,
						CrmDictTypeConstants.TYPE_HIGHEST_EDU,
						CrmDictTypeConstants.TYPE_SEX,
						CrmDictTypeConstants.TYPE_NATION,
						CrmDictTypeConstants.TYPE_CERT_TYPE,
						CrmDictTypeConstants.TYPE_ASSETS_LEVEL,
						CrmDictTypeConstants.TYPE_RISK_LEVEL,
						CrmDictTypeConstants.TYPE_PROFESSION));
	}

	/**
	 * 通过字典类型和标签查找字典项
	 *
	 * @param type 类型
	 * @param label 标签
	 * @return 同类型字典项
	 */
	@GetMapping("/item/label/{type}/{label}")
	@Cacheable(value = CacheConstants.DICT_DETAILS, key = "'SysDictItem:' + #type + ':' + #label", unless = "#result == null")
	public R<SysDictItem> getDictItemByTypeAndLabel(@PathVariable String type, @PathVariable String label) {
		return R.ok(sysDictItemService.getOne(Wrappers
				.<SysDictItem>query().lambda()
				.eq(SysDictItem::getType, type)
				.eq(SysDictItem::getLabel, label),false));
	}


	/**
	 * 分页查询
	 *
	 * @param page        分页对象
	 * @param sysDictItem 字典项
	 * @return
	 */
	@GetMapping("/item/page")
	public R getSysDictItemPage(Page page, SysDictItem sysDictItem) {
		return R.ok(sysDictItemService.page(page, query(sysDictItem)));
	}


	/**
	 * 通过id查询字典项
	 *
	 * @param id id
	 * @return R
	 */
	@GetMapping("/item/id/{id}")
	public R getDictItemById(@PathVariable("id") Integer id) {
		return R.ok(sysDictItemService.getById(id));
	}


	/**
	 * 新增字典项
	 *
	 * @param sysDictItem 字典项
	 * @return R
	 */
	@SysLog("新增字典项")
	@PostMapping("/item")
	@CacheEvict(value = CacheConstants.DICT_DETAILS, key = "'SysDictItem:' + #sysDictItem.type")
	public R save(@RequestBody SysDictItem sysDictItem) {
		return R.ok(sysDictItemService.save(sysDictItem));
	}


	/**
	 * 修改字典项
	 *
	 * @param sysDictItemDto 字典项
	 * @return R
	 */
	@SysLog("修改字典项")
	@PutMapping("/item")
	@Caching(evict = {
			@CacheEvict(value = CacheConstants.DICT_DETAILS, key = "'SysDictItem:' + #sysDictItemDto.oldType + ':' + #sysDictItemDto.oldValue"),
			@CacheEvict(value = CacheConstants.DICT_DETAILS, key = "'SysDictItem:' + #sysDictItemDto.oldType"),
			@CacheEvict(value = CacheConstants.DICT_DETAILS, key = "'SysDictItem:' + #sysDictItemDto.type")
	})
	public R updateById(@RequestBody SysDictItemDto sysDictItemDto) {
		SysDictItem sysDictItem = new SysDictItem();
		BeanUtils.copyProperties(sysDictItemDto, sysDictItem);
		return R.ok(sysDictItemService.updateById(sysDictItem));
	}


	/**
	 * 通过type-value删除字典项
	 *
	 * @param sysDictItem
	 * @return R
	 */
	@SysLog("通过type和value删除字典项")
	@DeleteMapping("/item")
	public R removeDictItemByTypeAndVaule(@RequestBody SysDictItem sysDictItem) {
		return R.ok(sysDictItemService.removeDictItemByTypeAndVaule(sysDictItem));
	}
}
